package com.hdu;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class CasLock {


    public static void main(String[] args) {
        CasLock casLock = new CasLock();
        new Thread(() -> {
            casLock.lock();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                casLock.unlock();
            }
        }).start();

        new Thread(() -> {
            casLock.lock();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                casLock.unlock();
            }
        }).start();

    }


    private final AtomicReference<Thread> lockThread = new AtomicReference<>();

    public void lock() {
        while (!lockThread.compareAndSet(null, Thread.currentThread())) {
            log.info("没有获得锁, 阻塞重试");
        }
        log.info("成功获得锁");
    }

    public void unlock() {
        if (lockThread.get() != Thread.currentThread()) {
            throw new IllegalArgumentException("this lock not belong to you");
        }
        if (!lockThread.compareAndSet(Thread.currentThread(), null)) {
            throw new IllegalArgumentException("unlock fail");
        }
        log.info("释放锁");
    }
}
